package com.tjsinfo.tjsoa.mail.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.tjsinfo.tjsoa.mail.dao.ITjsFoldEmailAnnexDAO;
import com.tjsinfo.tjsoa.mail.vo.TjsDeleteEmailAnnex;
import com.tjsinfo.tjsoa.mail.vo.TjsFoldEmailAnnex;

public class FlodAnnexIOAction extends Action{
	private ITjsFoldEmailAnnexDAO tjsFoldEmailAnnexDAO;

	public ITjsFoldEmailAnnexDAO getTjsFoldEmailAnnexDAO() {
		return tjsFoldEmailAnnexDAO;
	}

	public void setTjsFoldEmailAnnexDAO(ITjsFoldEmailAnnexDAO tjsFoldEmailAnnexDAO) {
		this.tjsFoldEmailAnnexDAO = tjsFoldEmailAnnexDAO;
	}

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String url = "error";
		// TODO Auto-generated method stub
		try {
			String id=request.getParameter("id");
			TjsFoldEmailAnnex expressFile = tjsFoldEmailAnnexDAO.selectByID(id);
			File file = new File(expressFile.getAnnexAddress()); 			
			String filename = file.getName();
			InputStream fis = new BufferedInputStream(new FileInputStream(expressFile.getAnnexAddress()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();		
			response.reset();
		    response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
	        response.addHeader("Content-Length", "" + file.length());
	        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	        response.setContentType("application/octet-stream");
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
			url = "ok";
		} catch (IOException ex) {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			ex.printStackTrace();
			return mapping.findForward("error");
		} catch(NullPointerException ex){
			return null;
		} catch (Exception ex){
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return mapping.findForward("error");
		}
		if ("ok".equals(url)) {
			return null;	
		}else {
			request.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return  mapping.findForward(url);
		}
	}
}

